﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using AutoMapper;
using Microsoft.EntityFrameworkCore;
using MyApplication.Dtos;
using MyEFCore;

namespace MyApplication
{
    public class ProductService : IProductService
    {
        private readonly IRepositoryManager _repositoryManager;
        private readonly IMapper _mapper;

        public ProductService(IRepositoryManager repositoryManager, IMapper mapper)
        {
            _repositoryManager = repositoryManager;
            _mapper = mapper;
        }

        public async Task<int> CreateNewProductAsync(CreateProductDto product)
        {
            var entity = _mapper.Map<Product>(product);
            _repositoryManager.Product.Create(entity);
            await _repositoryManager.SaveAsync();
            return entity.ProductId;
        }

        public async Task DeleteProductAsync(int id)
        {
            var p = _repositoryManager.Product.FindByCondition(x => x.ProductId == id, true).SingleOrDefault();
            if (p == null) return;
            _repositoryManager.Product.Delete(p);
            await _repositoryManager.SaveAsync();
        }

        public async Task<IQueryable<Product>> GetAllPrpoductsAsync()
        {
            var entities = _repositoryManager.Product.FindAll(false);
            await Task.CompletedTask;
            return entities;
        }

        public async Task<ProductDto> GetProductByIdAsync(int id)
        {
            var entity = await _repositoryManager.Product.FindByCondition(x => x.ProductId == id, false).SingleOrDefaultAsync();
            return _mapper.Map<ProductDto>(entity);
        }

        public async Task<ProductDto> GetProductByNameAsync(string name)
        {
            var entity = await _repositoryManager.Product.FindByCondition(x => x.Name == name, false).SingleOrDefaultAsync();
            return _mapper.Map<ProductDto>(entity);
        }

        public async Task UpdateProductAsync(int id, UpdateProductDto product)
        {
            var p = await _repositoryManager.Product.FindByCondition(x => x.ProductId == id, true).SingleOrDefaultAsync();
            _mapper.Map(product, p);
            await _repositoryManager.SaveAsync();
        }
    }
}
